package com.Jano.service.Impl;/**
 * @ClassName : loginServiceImpl
 * @Description :
 * @Author : Jano
 * @Date: 2022-07-24 19:17
 */

import com.Jano.constant.JwtConstant;
import com.Jano.dto.JsonResult;
import com.Jano.dto.LoginUser;
import com.Jano.entity.User;
import com.Jano.service.loginService;
import com.Jano.util.JwtTokenUtil;
import com.Jano.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zoumaoji
 * @date 2022/07/24 19:17
 **/
@Service
public class loginServiceImpl extends AbstractBaseServiceImpl implements loginService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisCache redisCache;

    @Override
    public JsonResult login(User user) {
        //AuthenticationManager authenticate 进行用户认证 注意这里的有参构造 两个 和 三个的情况是不同的  那么this.setAuthenticated(false);会出现未认证状态
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

        //如果认证没有通过,给出相应的提示
        throwIfNull(authenticate, "登陆失败！！！！！！");

        //如果认证通过了,使用userId生成一个jwt jwt存入JsonResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String userName = loginUser.getUser().getUserName();
        //签发token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtConstant.JWT_USER_NAME, userName);
        //签发jwtToken
        String jwtToken = JwtTokenUtil.getAccessToken(userId, claims);

        //把完整的用户信息存入redis userId作为key
        redisCache.setCacheObject("login:"+userId,loginUser);
        return new JsonResult().setCode(HttpStatus.OK.value()).setData(jwtToken);
    }


    @Override
    public JsonResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userid);
        return new JsonResult().setCode(HttpStatus.OK.value()).setData("退出成功");
    }
}
//public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {
//    // 序列化id
//    private static final long serialVersionUID = 530L;
//    // 一般指的是用户名
//    private final Object principal;
//    // 一般指的是密码
//    private Object credentials;
//
//    // 构造器
//    // principal  一般指的是用户名
//    // credentials  一般指的是密码
//    public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
//        // 初始化父类构造 权限集合为空
//        super((Collection)null);
//        this.principal = principal;
//        this.credentials = credentials;
//        // 设置是否已认证 默认为false
//        this.setAuthenticated(false);
//    }
//
//    // 构造器
//    // principal  一般指的是用户名
//    // credentials  一般指的是密码
//    // authorities 权限
//    public UsernamePasswordAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
//        // // 初始化父类构造 权限集合
//        super(authorities);
//        this.principal = principal;
//        this.credentials = credentials;
//        // 设置父类方法表示已经认证
//        super.setAuthenticated(true);
//    }
//
//    // 获取密码
//    public Object getCredentials() {
//        return this.credentials;
//    }
//    // 获取用户名
//    public Object getPrincipal() {
//        return this.principal;
//    }
//    // 设置是否已认证 默认为false
//    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
//        // 如果为true
//        // 抛出非法参数异常
//        if (isAuthenticated) {
//            throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
//        } else {
//            // 设置父类是否已认证
//            super.setAuthenticated(false);
//        }
//    }
//    // 擦除凭证
//    public void eraseCredentials() {
//        // 调用父类方法
//        super.eraseCredentials();
//        // 将密码设置为空
//        this.credentials = null;
//    }
//}

